<script setup>
import { ref, defineEmits, defineProps, onMounted, defineModel } from 'vue'

const emits = defineEmits(['change'])
const props = defineProps({
  categories: {
    type: Array,
    default: () => [],
  },
})

//当前选中的分类序号
const active = defineModel()

//切换分类事件
const change = (index) => {
  active.value = index
  const category = props.categories[index]
  emits('change', index, category)
}

//分类居中显示
const justifyCenter = ref(false)
const categoryRef = ref(null)

onMounted(() => {
  let width = 0
  Array.from(categoryRef.value.children).forEach((el) => {
    width += el.offsetWidth
  })
  justifyCenter.value = width < window.innerWidth
})
</script>

<template>
  <el-scrollbar>
    <div
      ref="categoryRef"
      class="flex flex-nowrap gap-1"
      :class="{ 'justify-center': justifyCenter }"
    >
      <template v-for="(category, index) in categories" :key="category.id">
        <div
          v-if="category.show !== false"
          :class="{ item: true, active: active === index }"
          @click="change(index)"
        >
          <div>{{ category.name }}</div>
        </div>
      </template>
    </div>
  </el-scrollbar>
</template>

<style scoped>
.item {
  @apply px-2 py-1 rounded-md text-sm cursor-pointer hover:bg-[--el-fill-color-dark] text-ellipsis whitespace-nowrap;
}

.item.active {
  @apply bg-[--el-color-primary-light-8] text-[--el-color-primary];
}
</style>
